/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * IssueForm.java
 *
 * Created on Aug 5, 2011, 3:51:34 PM
 */

package redclient.ui;

import com.toedter.calendar.JDateChooser;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import redclient.Items.CustomField;
import redclient.Items.Issue;
import redclient.Items.Project;
import redclient.client.Feedback;
import redclient.client.FeedbackType;
import redclient.client.RedManager;
import redclient.ui.layout.SpringUtilities;
import redclient.util.NumberParser;
import redclient.webclient.WebClientException;

/**
 *
 * @author Isaias
 */
public class IssueForm extends javax.swing.JFrame {

    private Project project;
    
    private Issue issue;
    
    private FileChooser fc = null;
    
    public IssueForm(Issue issue)
    {
        this();
        this.issue = issue;
    }
    public IssueForm(Project project)
    {
        this();
        this.project = project;
        populateNewIssue(null);

    }
    /** Creates new form IssueForm */
    public IssueForm() {
        initComponents();
    }

    private String token;

    private String action;

    private void populateNewIssue(Issue issue)
    {
        try
        {
            RedManager rm = RedManager.Connect(project.getCredentials());
            org.jsoup.nodes.Document doc = rm.GetIssueFields(project, issue, token, action);
            
            Elements labels = doc.select("label[for]");
            lblTracker.setText(labels.select("[for=issue_tracker_id]").text());
            lblSubject.setText(labels.select("[for=issue_subject]").text());
            String parentTaskLabel = labels.select("[for=issue_parent_issue_id]").text();
            if( parentTaskLabel != null && !"".equals(parentTaskLabel.trim()))
            {
                lblParentTask.setText(parentTaskLabel); // Not in HTML
                cmbParentTask.setEnabled(true);
            }
            else
            {
                lblParentTask.setText("Not available"); // Not in HTML
                cmbParentTask.setEnabled(false);
            }
            lblDesc.setText(labels.select("[for=issue_description]").text());
            lblStatus.setText(labels.select("[for=issue_status_id]").text());
            lblPriority.setText(labels.select("[for=issue_priority_id]").text());
            lblAssignedTo.setText(labels.select("[for=issue_assigned_to_id]").text());
            lblStartDate.setText(labels.select("[for=issue_start_date]").text());
            lblDueDate.setText(labels.select("[for=issue_due_date]").text());
            lblEstimatedTime.setText(labels.select("[for=issue_estimated_hours]").text());
            lblHours.setText(doc.select("#issue_estimated_hours").get(0).nextSibling().toString().trim());
            lblDoneRatio.setText(labels.select("[for=issue_done_ratio]").text());
            btnSave.setText(doc.select("input[name=commit]").attr("value"));

            // Populates tracker type
            if( cmbTracker.getItemCount() == 0 )
            {
                Element tracker = doc.select("#issue_tracker_id").first();
                populateComboBox(tracker, cmbTracker);
            }

            token = doc.select("input[name=authenticity_token]").first().attr("value");
            action = doc.select("input[name=commit]").first().attr("value");
            cmbTracker.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    Issue tmpIssue = new Issue();
                    tmpIssue.setTrakerId(Integer.parseInt(((HtmlOptionLike)cmbTracker.getSelectedItem()).getValue()));
                    tmpIssue.setSubject(textSubject.getText());
                    tmpIssue.setParentIssueId(cmbParentTask.getSelectedIndex() > -1 ? ((HtmlOptionLike)cmbStatus.getSelectedItem()).getValue() : null);
                    tmpIssue.setStatusId(Integer.parseInt(((HtmlOptionLike)cmbStatus.getSelectedItem()).getValue()));
                    tmpIssue.setPriorityId(Integer.parseInt(((HtmlOptionLike)cmbPriority.getSelectedItem()).getValue()));
                    tmpIssue.setStartDate(dcStartDate.getDate());
                    tmpIssue.setDueDate(dcDueDate.getDate());
                    Float estimatedTime = (Float)NumberParser.parseNumberValue(textEstimatedTime.getText(), Float.class);
                    tmpIssue.setEstimatedHours(estimatedTime != null ? estimatedTime : 0);
                    tmpIssue.setDoneRation(cmdDoneRatio.getSelectedIndex() * 10);
                    populateNewIssue(tmpIssue);
                }
            });
            
            // Populates current issues
            cmbParentTask.removeAllItems();
            cmbParentTask.addItem(new HtmlOptionLike("", false, ""));
            for( Issue pissue : project.getIssues() )
            {
                cmbParentTask.addItem(new HtmlOptionLike(pissue.getSubject(), false, pissue.getId()));
            }

            // Populates statuses
            Element status = doc.select("#issue_status_id").first();
            populateComboBox(status, cmbStatus);

            // Populate issue priority
            Element priority = doc.select("#issue_priority_id").first();
            populateComboBox(priority, cmbPriority);

            // Populate issue assigned to
            Element assigned = doc.select("#issue_assigned_to_id").first();
            populateComboBox(assigned, this.cmbAssignedTo);

            // Set default date
            dcStartDate.setDate(new Date());
            
            populateCustomFields(doc);
            
            System.gc();

        }
        catch(WebClientException wce)
        {
            JOptionPane.showMessageDialog(this, wce.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(this, "Unexpected error, please contact your administrator", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }


    private void populateCustomFields(org.jsoup.nodes.Document doc)
    {
        customFieldsPanel.removeAll();
        SpringLayout layout = new SpringLayout();
        customFieldsPanel.setLayout(layout);
        
        Elements eCustomLabels = doc.select("label[for^=issue_custom_field_values]");
        int requiredRows = 0;
        for(int i = 0; i < eCustomLabels.size(); i++)
        {
            Element eLabel = eCustomLabels.get(i);
            Element uEl = eLabel.nextElementSibling();
            
            String customLabel = null;
            if( "span".equals(uEl.tagName()) && "required".equals(uEl.attr("class")) ) {
                customLabel = eLabel.text() + " *";
                uEl = uEl.nextElementSibling();
            }
            else{
                customLabel = eLabel.text();
            }
            JLabel labelField = new JLabel(customLabel, JLabel.TRAILING);
            customFieldsPanel.add(labelField);
            if ( "input".equals(uEl.tagName()) )
            {
                if( "hidden".equalsIgnoreCase(uEl.attr("type")) )
                {
                    uEl = uEl.nextElementSibling();
                }
                if( "text".equalsIgnoreCase(uEl.attr("type"))){
                    if ( uEl.nextElementSibling() != null && "calendar-trigger".equals(uEl.nextElementSibling().attr("class")) )
                    {
                        JDateChooser dateField = new JDateChooser();
                        dateField.setName(uEl.attr("name"));
                        dateField.setSize(dcStartDate.getSize());
                        dateField.setMaximumSize(dateField.getSize());
                        dateField.setPreferredSize(dateField.getSize());
                        customFieldsPanel.add(dateField);
                    }
                    else
                    {
                        JTextField inputText = new JTextField();
                        inputText.setName(uEl.attr("name"));
                        inputText.setText(uEl.val());
                        inputText.setSize(textSubject.getSize());
                        inputText.setMaximumSize(inputText.getSize());
                        inputText.setPreferredSize(inputText.getSize());
                        customFieldsPanel.add(inputText);
                    }
                }
                else if ( "checkbox".equalsIgnoreCase(uEl.attr("type"))){
                    JCheckBox checkbox = new JCheckBox();
                    checkbox.setName(uEl.attr("name"));
                    checkbox.setSelected("1".equals(uEl.attr("value")));
                    customFieldsPanel.add(checkbox);
                }
            }
            else if ( "textarea".equals(uEl.tagName()) ){
                JTextArea textArea = new JTextArea();
                textArea.setRows(3);
                textArea.setName(uEl.attr("name"));
                textArea.setText(uEl.val());
                textArea.setSize(textDesc.getSize());
                textArea.setMaximumSize(textArea.getSize());
                textArea.setPreferredSize(textArea.getSize());
                labelField.setVerticalAlignment(JLabel.TOP);
                customFieldsPanel.add(textArea);
            }
            else if ( "select".equals(uEl.tagName() ) )
            {
                JComboBox selectField = new JComboBox();
                selectField.setName(uEl.attr("name"));
                populateComboBox(uEl, selectField);
                selectField.setSize(cmbParentTask.getSize());
                selectField.setMaximumSize(selectField.getSize());
                selectField.setPreferredSize(selectField.getSize());
                customFieldsPanel.add(selectField);
            }
            requiredRows++;
            //layout.putConstraint(SpringLayout.WEST, labelField, 5,  SpringLayout.WEST, customFieldsPanel);
            //layout.putConstraint(SpringLayout.NORTH, labelField,  5, SpringLayout.NORTH, customFieldsPanel);
        }
        
        SpringUtilities.makeCompactGrid(customFieldsPanel,
                                requiredRows, 2, //rows, cols
                                6, 6,        //initX, initY
                                6, 6);
        
        this.setSize(this.getWidth(), jMainPanel.getY()+jMainPanel.getHeight() + customFieldsPanel.getPreferredSize().height+60);
        
        
    }
    
    private void populateComboBox(Element element, JComboBox combo)
    {
        combo.removeAllItems();
        int selectedIndex = 0;
        for( Iterator<Node> ioption = element.childNodes().iterator(); ioption.hasNext();)
        {
            Node rawNode = ioption.next();
            if( rawNode instanceof Element)
            {
                Element option = (Element)rawNode;
                if ( option.tagName().equals("option"))
                {
                    combo.addItem(
                                        new HtmlOptionLike(option.text(),
                                               "selected".equals(option.attr("selected")),
                                               option.attributes().get("value")
                                           ));
                    if( option.attr("selected") == "selected" )
                    {
                        combo.setSelectedIndex(selectedIndex);
                    }
                }
                selectedIndex++;
            }
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMainPanel = new javax.swing.JPanel();
        lblTracker = new javax.swing.JLabel();
        lblSubject = new javax.swing.JLabel();
        lblParentTask = new javax.swing.JLabel();
        cmbTracker = new javax.swing.JComboBox();
        textSubject = new javax.swing.JTextField();
        cmbParentTask = new javax.swing.JComboBox();
        lblDesc = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textDesc = new javax.swing.JTextArea();
        lblStatus = new javax.swing.JLabel();
        lblPriority = new javax.swing.JLabel();
        lblAssignedTo = new javax.swing.JLabel();
        cmbStatus = new javax.swing.JComboBox();
        cmbPriority = new javax.swing.JComboBox();
        cmdDoneRatio = new javax.swing.JComboBox();
        lblStartDate = new javax.swing.JLabel();
        dcStartDate = new com.toedter.calendar.JDateChooser();
        lblDueDate = new javax.swing.JLabel();
        dcDueDate = new com.toedter.calendar.JDateChooser();
        textEstimatedTime = new javax.swing.JTextField();
        cmbAssignedTo = new javax.swing.JComboBox();
        lblDoneRatio = new javax.swing.JLabel();
        lblHours = new javax.swing.JLabel();
        lblEstimatedTime = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        btnSave1 = new javax.swing.JButton();
        customFieldsPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                addCalendars(evt);
            }
        });

        lblTracker.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblTracker.setText("Tracker *");

        lblSubject.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblSubject.setText("Subject *");

        lblParentTask.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblParentTask.setText("Parent task");

        lblDesc.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblDesc.setText("Description");

        textDesc.setColumns(20);
        textDesc.setRows(5);
        jScrollPane1.setViewportView(textDesc);

        lblStatus.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblStatus.setText("Status *");

        lblPriority.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblPriority.setText("Priority *");

        lblAssignedTo.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblAssignedTo.setText("Assigned to");

        cmdDoneRatio.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%. 100%" }));

        lblStartDate.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblStartDate.setText("Start date");

        lblDueDate.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblDueDate.setText("Due date");

        lblDoneRatio.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblDoneRatio.setText("% Done");

        lblHours.setText("Hours");

        lblEstimatedTime.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        lblEstimatedTime.setText("Estimated time");

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_ok_16px.png"))); // NOI18N
        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/folder_open.png"))); // NOI18N
        jButton1.setText("Select Files");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btnSave1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_remove_file.png"))); // NOI18N
        btnSave1.setText("Cancel");
        btnSave1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSave1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jMainPanelLayout = new javax.swing.GroupLayout(jMainPanel);
        jMainPanel.setLayout(jMainPanelLayout);
        jMainPanelLayout.setHorizontalGroup(
            jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jMainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(lblAssignedTo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblDesc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblParentTask, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblPriority, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE)
                    .addComponent(lblSubject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblTracker, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                    .addGroup(jMainPanelLayout.createSequentialGroup()
                        .addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(3, 3, 3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jMainPanelLayout.createSequentialGroup()
                        .addComponent(cmbTracker, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 317, Short.MAX_VALUE)
                        .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jMainPanelLayout.createSequentialGroup()
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(textSubject, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbParentTask, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                        .addComponent(btnSave1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jMainPanelLayout.createSequentialGroup()
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(cmbPriority, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cmbStatus, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cmbAssignedTo, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(43, 43, 43)
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lblDoneRatio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblEstimatedTime, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblStartDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblDueDate, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dcDueDate, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                            .addComponent(dcStartDate, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                            .addComponent(cmdDoneRatio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jMainPanelLayout.createSequentialGroup()
                                .addComponent(textEstimatedTime, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(lblHours, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 532, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(127, 127, 127))
        );
        jMainPanelLayout.setVerticalGroup(
            jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jMainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTracker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTracker)
                    .addComponent(btnSave))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblSubject)
                    .addComponent(btnSave1))
                .addGap(5, 5, 5)
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbParentTask, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblParentTask))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDesc))
                .addGap(18, 18, 18)
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblStatus)
                        .addComponent(lblStartDate))
                    .addComponent(dcStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblPriority)
                        .addComponent(cmbPriority, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblDueDate))
                    .addComponent(dcDueDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jMainPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(textEstimatedTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblEstimatedTime)
                            .addComponent(lblHours))
                        .addGap(18, 18, 18)
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmdDoneRatio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblDoneRatio)))
                    .addGroup(jMainPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmbAssignedTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblAssignedTo))
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout customFieldsPanelLayout = new javax.swing.GroupLayout(customFieldsPanel);
        customFieldsPanel.setLayout(customFieldsPanelLayout);
        customFieldsPanelLayout.setHorizontalGroup(
            customFieldsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 790, Short.MAX_VALUE)
        );
        customFieldsPanelLayout.setVerticalGroup(
            customFieldsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 77, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(customFieldsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jMainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(customFieldsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addCalendars(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_addCalendars
        
    }//GEN-LAST:event_addCalendars

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    Issue issue = new Issue();
    issue.setProject(project);
    issue.setProjectId(project.getProjectId());
    issue.setTrakerId(Integer.parseInt(((HtmlOptionLike)cmbTracker.getSelectedItem()).getValue()));
    issue.setSubject(textSubject.getText());
    issue.setParentIssueId(((HtmlOptionLike)cmbParentTask.getSelectedItem()).getValue());
    issue.setDescription(textDesc.getText());
    issue.setStatusId(Integer.valueOf(((HtmlOptionLike)cmbStatus.getSelectedItem()).getValue()));
    issue.setPriorityId(Integer.valueOf(((HtmlOptionLike)cmbPriority.getSelectedItem()).getValue()));
    try
    {
        issue.setAssignedToId(Integer.valueOf(((HtmlOptionLike)cmbAssignedTo.getSelectedItem()).getValue()));
    }
    catch(NumberFormatException nfe)
    {
        issue.setAssignedToId(-1);
    }
    
    issue.setStartDate(dcStartDate.getDate());
    issue.setDueDate(dcDueDate.getDate());
    try
    {
        issue.setEstimatedHours(Float.valueOf(textEstimatedTime.getText()));
    }
    catch(NumberFormatException nfe)
    {
        issue.setEstimatedHours(-1);
    }
    issue.setDoneRation(cmdDoneRatio.getSelectedIndex()*10);
    List<CustomField> customFields = new ArrayList<CustomField>();
    for(Component component : this.customFieldsPanel.getComponents())
    {
        CustomField cf = null;
        if( component instanceof JTextField)
        {
            cf = new CustomField();
            cf.setValue(((JTextField)component).getText());
        }
        else if( component instanceof JTextArea)
        {
            cf = new CustomField();
            cf.setValue(((JTextArea)component).getText());
        }
        else if( component instanceof JComboBox)
        {
            cf = new CustomField();
            cf.setValue(((HtmlOptionLike)(((JComboBox)component).getSelectedItem())).getValue());
        }
        else if(component instanceof JDateChooser)
        {
            cf = new CustomField();
            cf.setValue(((JDateChooser)component).getDate().toString());
        }
        else if(component instanceof JCheckBox)
        {
            cf = new CustomField();
            cf.setValue(((JCheckBox)component).isSelected()?"1":"0");
        }
        
        if( cf != null )
        {
            cf.setName(component.getName());
            customFields.add(cf);
        }
    }
    
    if(!customFields.isEmpty())
    {
        issue.setCustomFileds(customFields);
    }
    
    File[] files = null;
    String[] descs = null;
    if( fc != null )
    {
        files = fc.getSelectedFiles();
        descs = fc.getDescriptions();
    }
    
    
    //File[] files = new File[]{new File("C:\\Users\\Isaias\\Downloads\\mailpv\\mailpv.chm")};
    //String[] descs = {"Nomás es de pruebas"};
    try
    {
        RedManager rm = RedManager.Connect(project.getCredentials());
        Feedback feedback = rm.saveIssue(issue, token, files, descs);
        if( feedback != null )
        {
            if( feedback.getFeedbackType() == FeedbackType.VALIDATION_ERROR )
            {
                StringBuilder text = new StringBuilder(feedback.getHeader());
                for(String message : feedback.getMessages())
                {
                    text.append("\r\n- ").append(message);
                }
                JOptionPane.showMessageDialog(this, text.toString(), feedback.getCaption(), JOptionPane.ERROR_MESSAGE);
            }
            else // if( feedback.getFeedbackType() == FeedbackType.SUBMIT_SUCEES)
            {
                JOptionPane.showMessageDialog(this, feedback.getHeader(), feedback.getCaption(), JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Unexpected result when saving new issue", "Unexpected result", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    catch(WebClientException wce)
    {
        JOptionPane.showMessageDialog(this, wce.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(this, "Unexpected error, please contact your administrator", "Error", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_btnSaveActionPerformed


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    if( fc == null )
    {
        fc = new FileChooser();
    }
    fc.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed

    private void btnSave1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSave1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSave1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new IssueForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSave1;
    private javax.swing.JComboBox cmbAssignedTo;
    private javax.swing.JComboBox cmbParentTask;
    private javax.swing.JComboBox cmbPriority;
    private javax.swing.JComboBox cmbStatus;
    private javax.swing.JComboBox cmbTracker;
    private javax.swing.JComboBox cmdDoneRatio;
    private javax.swing.JPanel customFieldsPanel;
    private com.toedter.calendar.JDateChooser dcDueDate;
    private com.toedter.calendar.JDateChooser dcStartDate;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jMainPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAssignedTo;
    private javax.swing.JLabel lblDesc;
    private javax.swing.JLabel lblDoneRatio;
    private javax.swing.JLabel lblDueDate;
    private javax.swing.JLabel lblEstimatedTime;
    private javax.swing.JLabel lblHours;
    private javax.swing.JLabel lblParentTask;
    private javax.swing.JLabel lblPriority;
    private javax.swing.JLabel lblStartDate;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JLabel lblSubject;
    private javax.swing.JLabel lblTracker;
    private javax.swing.JTextArea textDesc;
    private javax.swing.JTextField textEstimatedTime;
    private javax.swing.JTextField textSubject;
    // End of variables declaration//GEN-END:variables


}
